package com.example.config;


import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ClientConfig {

    private static String host = "127.0.0.1";
    private static int port = 8002;
    private Channel channel;

    ClientConfig() {
        init();
    }

    private void init() {
        final EventLoopGroup group = new NioEventLoopGroup();

        Bootstrap bootstrap = new Bootstrap();
        bootstrap.group(group).channel(NioSocketChannel.class)  // 使用NioSocketChannel来作为连接用的channel类
                .handler(new ChannelInitializer<SocketChannel>() { // 绑定连接初始化器
                    @Override
                    public void initChannel(SocketChannel ch) throws Exception {
                        System.out.println("正在连接中...");
                        ChannelPipeline pipeline = ch.pipeline();
//                        pipeline.addLast(new RpcEncoder(RpcRequest.class)); //编码request
//                        pipeline.addLast(new RpcDecoder(RpcResponse.class)); //解码response
//                        pipeline.addLast(new ClientHandler()); //客户端处理类
                    }
                });

        try {
            ChannelFuture future = bootstrap.connect(host, port).sync();

            future.addListener(new ChannelFutureListener() {

                @Override
                public void operationComplete(ChannelFuture arg0) throws Exception {
                    if (future.isSuccess()) {
                        System.out.println("连接服务器成功");

                    } else {
                        System.out.println("连接服务器失败");
                        future.cause().printStackTrace();
                        group.shutdownGracefully(); //关闭线程组
                    }
                }
            });

            this.channel = future.channel();

        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public Channel getChannel() {
        return channel;
    }
}
